#include "XLand.h"
#include "Utils.h"
#include <web/HttpServer.h>
#include <ll/api/plugin/NativePlugin.h>
#include <RemoteCallAPI.h>
using namespace hv;
HttpService router;
HttpServer  server;

inline namespace Utils {
    string getLocalIP() {
        char hostname[1024];
        if (gethostname(hostname, sizeof(hostname)) == -1) {
            std::cerr << "Failed to get hostname: " << std::strerror(errno) << std::endl;
            return "127.0.0.1";
        }
        struct hostent* host = gethostbyname(hostname);
        if (host == nullptr) {
            std::cerr << "Failed to get host information: " << std::strerror(errno) << std::endl;
            return "127.0.0.1";
        }

        struct in_addr** addr_list = (struct in_addr**)host->h_addr_list;
        for (int i = 0; addr_list[i] != nullptr; ++i) {
            return inet_ntoa(*addr_list[i]);
        }
        return "127.0.0.1";
    }
    void webServer() {
        router.Static("/", config.WebPath.c_str());
        router.GET("/land/list", [](const HttpContextPtr& ctx) {
            auto lands = XLand::listLand(0);
            hv::Json resp;
            auto value = ctx->param("value");
            for(auto& item : *lands) {
                hv::Json temp;
                temp["ID"]    = item.id;
                temp["name"]  = item.name;
                temp["range"] = fmt::format("{} ~ {}", item.minPt.toString(), item.maxPt.toString());
                resp.push_back(temp);
            }
            return ctx->send(resp.dump(2));
        });
        router.GET("/land/search/{value}", [](const HttpContextPtr& ctx) {
            hv::Json resp;
            auto value = ctx->param("value");
            auto lands = XLand::searchLand(value);
            for(auto& item : *lands) {
                hv::Json temp;
                temp["ID"]    = item.id;
                temp["name"]  = item.name;
                temp["range"] = fmt::format("{} ~ {}", item.minPt.toString(), item.maxPt.toString());
                resp.push_back(temp);
            }
            return ctx->send(resp.dump(2));
        });
        server.service = &router;
        server.port    = config.port;
        server.setThreadNum(4);
    #if TEST_HTTPS
        server.https_port = 8443;
        hssl_ctx_opt_t param;
        memset(&param, 0, sizeof(param));
        param.crt_file = "cert/server.crt";
        param.key_file = "cert/server.key";
        param.endpoint = HSSL_SERVER;
        if (server.newSslCtx(&param) != 0) {
            fprintf(stderr, "new SSL_CTX failed!\n");
            return -20;
        }
    #endif
        server.start();
        logger.info("API服务器已部署到 http://{}:{}", getLocalIP(), config.port);
    }
}; // end mamespace Utils

